package com.adee.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class GroupChatServer {
    private int port;
    public GroupChatServer(int port) {
        this.port = port;
    }
    public static void main(String[] args) {
        new GroupChatServer(7000).run();
    }
    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // handler发生在连接初始化的时候，childHandler发生在连接建立好之后
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 获取到pipeLine
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入一个心跳检测handler
                            /*
                            * 为什么要在server端对客户端进行心跳检测，因为有时候server端无法感知客户端断开
                            * 参数说明：
                            * long readerIdleTime: 表示多长时间没读，就会发送一个心跳检测包
                            * long writerIdleTime: 表示多长时间没写，就会发送一个心跳检测包
                            * long allIdleTime: 表示多长时间没读写，就会发送一个心跳检测包
                            * 当IdleStateEvent触发后，就会传递给pipeLine的下一个handler去处理，调用下一个handler的userEventTriggered方法
                            * */
                            pipeline.addLast(new IdleStateHandler(10, 10, 10, TimeUnit.SECONDS));
                            // 加入一个对空闲检测进一步处理的自定义handler
                            pipeline.addLast(new GroupChatServerHeartBeatHandler());
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new GroupChatServerHandler());

                        }
                    });
            System.out.println("netty 服务器已启动，port=" + port);
            ChannelFuture future = bootstrap.bind(port).sync();
            // 阻塞监听关闭
            future.channel().closeFuture().sync();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
